<?php
class PackageContentController extends CBaseController
{		
	
	public function __construct($config=null) 
    { 
      parent::__construct($config);	  
    } 
	
	public function init($tpl)
	{
		parent::init($tpl);
		$this->reqLogin();
		$this->templator->addViewsDir(dirname(__FILE__).'/../views');
		$this->templator->assign('menu','content');
	}
	
	
	public function assign()
	{
		$id = $_POST['id'];
		$content_ids = $_POST['content_ids'];
		$package = R::load('travelpackage',$id);		
		foreach($content_ids as $content_id)
		{
			$content = R::load('content',$content_id);
			$fitsinto=$_POST[$content_id.'_fitsinto'];
			R::associate( $package, $content,array('fitsinto'=>$fitsinto));
		}
		$this->contents($id);
	}
	
	public function unassign()
	{
		$id = $_GET['id'];
		$package = R::load('travelpackage',$id);
		$content_id = $_GET['content_id'];
		$content = R::load('content',$content_id);
		R::unassociate( $package, $content );
		$this->contents();
	}
	
	public function contents($id=null)
	{
		if(!isset($id))
		$id = $_GET['id'];
		$package = R::load('travelpackage',$id);
		$assignedContents= R::related( $package, 'content' );
		foreach ($assignedContents as $content) {
			$keys=R::$extAssocManager->related($package,'content',TRUE,'content_id='.$content->id);
			$ref=R::load('content_travelpackage',$keys[0]);
			$content['fitsinto']=$ref->fitsinto;
		}
		$this->templator->assign('package',$package);		
		$this->templator->assign('contents',array_merge($assignedContents, array()));
		$this->templator->display('content/package_content.html');
	}
	
	public function select()
	{
		$id = $_POST['id'];
		$package = R::load('travelpackage',$id);
		$assignedContents= R::related( $package, 'content' );		
		$allContents = R::findAll('content');
		$contents =array_diff($allContents, $assignedContents);
		$this->templator->assign('package',$package);
		$this->templator->assign('contents',array_merge($contents, array()));
		$this->templator->display('content/content_list.html');
	}
	
}	